from flask_shop.utils.response_message import *
from flask import jsonify, g
from flask_shop.apis.user_module.user_models import *
from flask_shop.utils.tokens import generate_auth_token, login_required
from flask import request
from flask_restful import Resource, reqparse
from werkzeug.exceptions import BadRequest
from sqlalchemy import or_
import re
from ..classes import FArgument



class Register(Resource):
    """
    注册新用户，只有超级管理员才有权限
    """

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(FArgument(name="account", type=str, required=True))
        parser.add_argument(FArgument(name="pwd", type=str, required=True))
        parser.add_argument(FArgument(name='check_pwd', type=str, required=True))
        parser.add_argument(FArgument(name="name", type=str, required=True))
        parser.add_argument(FArgument(name="phone", type=str, required=False))
        parser.add_argument(FArgument(name="email", type=str, required=True))
        parser.add_argument(FArgument(name="role_id", type=int, required=True))
        print(request)
        print(request)
        try:
            args = parser.parse_args()
            account = args.get('account')
            pwd = args.get('pwd')
            check_pwd = args.get('check_pwd')
            name = args.get('name')
            phone = args.get('phone')
            email = args.get('email')
            role_id = args.get('role_id')

            if len(account) < 2:
                return get_response(type=ResponseType.field_error, msg="账号长度最少为2")
            if len(pwd) < 6:
                return get_response(type=ResponseType.field_error, msg="密码长度最少为6")
            if len(name) < 2:
                return get_response(type=ResponseType.field_error, msg="姓名长度最少为2")
            if pwd != check_pwd:
                return get_response(type=ResponseType.field_error, msg="两次密码不一致")
            if phone and not re.match(r'1[345678]\d{9}', phone):
                return get_response(type=ResponseType.field_error, msg="手机号码有误")
            if not re.match(r'^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$', email):
                return get_response(type=ResponseType.field_error, msg="邮箱格式错误")

            encrypted_pwd = User.encrypt_password(pwd)
            new_user = User(account=account, pwd=encrypted_pwd, name=name, phone=phone, email=email, role_id=role_id)
            db.session.add(new_user)
            db.session.commit()
            return get_response(type=ResponseType.success, msg="注册成功")

        except Exception as e:
            return get_error_response(e)


class Login(Resource):
    def post(self):
        data: dict = request.json
        account = data.get('account')
        pwd = data.get('pwd')

        print(type(request.json))

        if not all([account, pwd]):
            return get_response(type=ResponseType.field_missing)
        if len(account) > 1:
            user_ins: User = User.query.filter_by(account=account).first()
            if user_ins:
                if User.check_password(encrypted_pwd=user_ins.pwd, pwd=pwd):
                    token = generate_auth_token(user_ins.id)
                    resp_dict: dict = user_ins.dict()
                    resp_dict["token"] = token
                    resp_dict.pop("pwd")
                    return get_response(ResponseType.success, resp_dict)
        return get_response(ResponseType.user_operate_error, msg="用户名或密码错误")


class GetUserInfo(Resource):
    @login_required
    def get(self):
        user_id = g.user_id
        try:
            user_ins = User.query.filter_by(id=user_id).first()
            if user_ins:
                return get_response(ResponseType.success, user_ins.dict())
            else:
                return get_response(ResponseType.field_error, msg="获取用户信息失败")
        except Exception as e:
            return get_response(ResponseType.server_error, msg=f"{e}")


class ResetUserPassword(Resource):
    # 重置用户密码为123456
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(FArgument(name='id', type=int))
        try:
            args = parser.parse_args()
            id = args.get('id')
            user_ins: User = User.query.filter_by(id=id).first()
            user_ins.pwd = User.encrypt_password('123456')
            db.session.commit()
            return get_response(ResponseType.success)
        except Exception as e:
            rsp = get_error_response(e)
            return rsp


class DeleteUser(Resource):
    # 删除用户
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(FArgument(name='id', type=int))
        try:
            args = parser.parse_args()
            id = args.get('id')
            user_ins: User = User.query.filter_by(id=id).first()
            db.session.delete(user_ins)
            db.session.commit()
            return get_response(ResponseType.success)
        except Exception as e:
            rsp = get_error_response(e)
            return rsp


class UpdateUserInfo(Resource):
    # 更新用户信息
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(FArgument(name='id', type=int))
        parser.add_argument(FArgument(name='account', type=str))
        parser.add_argument(FArgument(name='name', type=str))
        parser.add_argument(FArgument(name='email', type=str))
        parser.add_argument(FArgument(name='role_id', type=int))

        try:
            args = parser.parse_args()
            id = args.get('id')
            account = args.get('account')
            name = args.get('name')
            email = args.get('email')
            role_id = args.get('role_id')

            user_ins: User = User.query.filter_by(id=id).first()
            if user_ins:
                user_ins.account = account
                user_ins.name = name
                user_ins.email = email
                user_ins.role_id = role_id
                db.session.commit()
                return get_response(ResponseType.success)
            else:
                return get_response(ResponseType.field_error, msg="未查询到此用户")
        except Exception as e:
            rsp = get_error_response(e)
            return rsp


class GetUserList(Resource):
    """
    获取用户列表
    """

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument(FArgument(name="searchText", type=str, required=False))
        parser.add_argument(FArgument(name="pageNO", type=int, default=1))
        parser.add_argument(FArgument(name="pageSize", type=int, default=20))
        try:
            args = parser.parse_args()
            searchText = args.get('searchText')
            pageNO = args.get('pageNO')
            pageSize = args.get('pageSize')
            if pageNO < 1 or pageSize < 1:
                return get_response(type=ResponseType.field_error, msg="参数错误：pageNO >= 1，pageSize >= 1")
            if searchText:
                users_page = User.query.filter(
                    or_(User.name.like(f'%{searchText}%'), User.account.like(f'%{searchText}%'))).paginate(page=pageNO,
                                                                                                           per_page=pageSize)
                # users_page = User.query(User.name, User.id).filter(
                #     User.name.like(f'%{searchText}%')).paginate(page=pageNO,
                #                                                                                            per_page=pageSize)
            else:
                users_page = User.query.paginate(page=pageNO, per_page=pageSize)

            users: [User] = []
            for item in users_page.items:
                user_dict = item.dict()
                user_dict["role"] = item.backref_role.dict()
                del user_dict["pwd"]
                users.append(user_dict)
            return get_page_response(key='users', data=users, pagination=users_page)
        except BadRequest as e:
            error_msg = e.data.get("message")
            return get_response(ResponseType.field_error, msg=error_msg)
        except Exception as e:
            return get_response(ResponseType.field_error, msg=f"{e}")


class CheckToken(Resource):
    @login_required
    def post(self):
        return get_response(ResponseType.success)


# class GetMenu(Resource):
#     """
#     获取菜单列表
#     """
#
#     def get(self):
#         menus = Menu.query.filter(Menu.level == 1).all()
#         print(type(jsonify(menus).json))
#         return get_response(ResponseType.success, jsonify(menus).json)


class GetRoleList(Resource):
    """
    获取角色列表
    """

    def post(self):
        role_list = Role.query.all()
        return get_response(ResponseType.success, jsonify(role_list).json)
